<template>
  <div class="container">
    <header class="header"></header>
    <main class="main">
      <div class="main-content">
        <section class="main-item" v-for="item in list" :key="item.id">
          {{ item.name }}
        </section>
      </div>
      <div class="loading">loading...</div>
    </main>
    <footer class="footer"></footer>
  </div>
</template>

<script>
import axios from 'axios'

function createData({ page = 1, size = 5 }) {
  return new Promise((resolve, reject) => {
    const data = []
    for (let i = 0; i < 100; i++) {
      data.push({
        id: i,
        name: '苹果' + i,
      })
    }
    resolve({
      code: 0,
      msg: 'success',
      data: data.slice((page - 1) * size, page * size),
    })
  })
}

export default {
  data() {
    return {
      list: [],
      page: 1,
    }
  },
  created() {
    // 第一次请求数据
    this.getData({})
  },
  // 监听dom
  mounted() {
    const io = new IntersectionObserver((entries) => {
      if (entries[0].intersectionRatio <= 0) return
      this.page++
      console.log('page:', this.page)
      this.getData({ page: this.page })
      console.log('我到底部了')
    })
    // start observing
    io.observe(document.querySelector('.loading'))
  },
  methods: {
    async getData({ page = this.page }) {
      const res = await createData({ page })
      console.log('res:', res.data)
      this.list = [...this.list, ...res.data]
    },
  },
}
</script>

<style lang="scss">
* {
  margin: 0;
  padding: 0;
  list-style: none;
}
html,
body,
#app {
  width: 100%;
  height: 100%;
}
.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .header {
    height: 45px;
    background: lightcoral;
  }
  .main {
    flex: 1;
    overflow: auto;
    .loading {
      height: 50px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 30px;
    }
    .main-item {
      height: 300px;
      width: 90%;
      margin: 5px auto;
      background: lightblue;
      border-radius: 5px;
    }
  }
  .footer {
    height: 45px;
    background: lightcoral;
  }
}
</style>
